package cn.edu.ncut.cs.springboot.petmanagementsystem.service.Impl;

import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.*;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.*;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ShoppingCartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private PetMapper petMapper;

    @Override
    @Transactional(rollbackOn = Exception.class)
    public Order createOrder(Long userId, List<Long> cartIds, String shippingAddress, String receiverName, String receiverPhone) {
        if (userId == null || cartIds == null || cartIds.isEmpty()) {
            throw new IllegalArgumentException("参数不完整");
        }

        // 查询购物车商品
        List<ShoppingCart> cartItems = cartMapper.selectBatchIds(cartIds);
        if (cartItems.isEmpty()) {
            throw new IllegalArgumentException("购物车为空");
        }

        // 计算总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (ShoppingCart cart : cartItems) {
            if (cart.getProductType() == 1) {
                // 宠物
                Pet pet = petMapper.selectById(cart.getProductId());
                if (pet != null && pet.getPrice() != null) {
                    totalAmount = totalAmount.add(pet.getPrice().multiply(new BigDecimal(cart.getQuantity())));
                }
            } else if (cart.getProductType() == 2) {
                // 商品
                Product product = productMapper.selectById(cart.getProductId());
                if (product != null && product.getPrice() != null) {
                    totalAmount = totalAmount.add(product.getPrice().multiply(new BigDecimal(cart.getQuantity())));
                }
            }
        }

        // 创建订单
        Order order = new Order();
        order.setOrderNo("ORD" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8).toUpperCase());
        order.setUserId(userId);
        order.setTotalAmount(totalAmount);
        order.setPaymentAmount(totalAmount);
        order.setOrderStatus(1); // 待付款
        order.setShippingAddress(shippingAddress);
        order.setReceiverName(receiverName);
        order.setReceiverPhone(receiverPhone);
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());

        orderMapper.insert(order);

        // 创建订单明细
        for (ShoppingCart cart : cartItems) {
            OrderItem item = new OrderItem();
            item.setOrderId(order.getId());
            item.setProductType(cart.getProductType());
            item.setProductId(cart.getProductId());
            item.setQuantity(cart.getQuantity());

            if (cart.getProductType() == 1) {
                Pet pet = petMapper.selectById(cart.getProductId());
                if (pet != null) {
                    item.setProductName(pet.getPetName());
                    item.setProductImage(pet.getMainImage());
                    item.setUnitPrice(pet.getPrice());
                    item.setTotalPrice(pet.getPrice().multiply(new BigDecimal(cart.getQuantity())));
                }
            } else if (cart.getProductType() == 2) {
                Product product = productMapper.selectById(cart.getProductId());
                if (product != null) {
                    item.setProductName(product.getProductName());
                    item.setProductImage(product.getMainImage());
                    item.setUnitPrice(product.getPrice());
                    item.setTotalPrice(product.getPrice().multiply(new BigDecimal(cart.getQuantity())));
                }
            }

            item.setCreateTime(LocalDateTime.now());
            orderItemMapper.insert(item);
        }

        // 删除购物车
        cartMapper.deleteBatchIds(cartIds);

        return order;
    }

    @Override
    public IPage<Order> getOrderList(Long userId, Integer pageNum, Integer pageSize) {
        Page<Order> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId);
        wrapper.orderByDesc(Order::getCreateTime);
        return orderMapper.selectPage(page, wrapper);
    }

    @Override
    public Order getOrderDetail(Long orderId, Long userId) {
        if (orderId == null || userId == null) {
            return null;
        }

        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getId, orderId)
                .eq(Order::getUserId, userId);
        return orderMapper.selectOne(wrapper);
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean updateOrderStatus(Long orderId, Integer status) {
        if (orderId == null || status == null) {
            return false;
        }

        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return false;
        }

        order.setOrderStatus(status);
        order.setUpdateTime(LocalDateTime.now());

        // 根据状态设置相应时间
        if (status == 2) { // 已付款
            order.setPaymentTime(LocalDateTime.now());
        } else if (status == 3) { // 已发货
            order.setShippingTime(LocalDateTime.now());
        } else if (status == 4) { // 已完成
            order.setCompleteTime(LocalDateTime.now());
        }

        int result = orderMapper.updateById(order);
        return result > 0;
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean cancelOrder(Long orderId, Long userId) {
        if (orderId == null || userId == null) {
            return false;
        }

        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return false;
        }

        // 验证订单所有权
        if (!order.getUserId().equals(userId)) {
            throw new IllegalArgumentException("无权操作此订单");
        }

        // 只有待付款和已付款状态可以取消
        if (order.getOrderStatus() != 1 && order.getOrderStatus() != 2) {
            throw new IllegalArgumentException("该订单状态不允许取消");
        }

        // 如果已付款，需要退款
        if (order.getOrderStatus() == 2) {
            // 这里可以调用退款接口
            log.info("订单已付款，需要进行退款处理: {}", orderId);
        }

        order.setOrderStatus(5); // 已取消
        order.setUpdateTime(LocalDateTime.now());
        int result = orderMapper.updateById(order);
        return result > 0;
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean confirmOrder(Long orderId, Long userId) {
        if (orderId == null || userId == null) {
            return false;
        }

        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return false;
        }

        // 验证订单所有权
        if (!order.getUserId().equals(userId)) {
            throw new IllegalArgumentException("无权操作此订单");
        }

        // 只有已发货状态可以确认收货
        if (order.getOrderStatus() != 3) {
            throw new IllegalArgumentException("该订单状态不允许确认收货");
        }

        order.setOrderStatus(4); // 已完成
        order.setCompleteTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        int result = orderMapper.updateById(order);
        return result > 0;
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean payOrder(Long orderId, Long userId, Integer paymentMethod) {
        if (orderId == null || userId == null || paymentMethod == null) {
            return false;
        }

        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return false;
        }

        // 验证订单所有权
        if (!order.getUserId().equals(userId)) {
            throw new IllegalArgumentException("无权操作此订单");
        }

        // 只有待付款状态可以支付
        if (order.getOrderStatus() != 1) {
            throw new IllegalArgumentException("该订单状态不允许支付");
        }

        // 这里应该调用第三方支付接口
        log.info("调用支付接口，订单ID: {}, 支付方式: {}, 金额: {}", orderId, paymentMethod, order.getPaymentAmount());

        // 模拟支付成功
        order.setOrderStatus(2); // 已付款
        order.setPaymentMethod(paymentMethod);
        order.setPaymentTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        int result = orderMapper.updateById(order);
        return result > 0;
    }

    @Override
    public Integer getOrderStatus(Long orderId, Long userId) {
        if (orderId == null || userId == null) {
            return null;
        }

        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return null;
        }

        // 验证订单所有权
        if (!order.getUserId().equals(userId)) {
            throw new IllegalArgumentException("无权查看此订单");
        }

        return order.getOrderStatus();
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean refundOrder(Long orderId, Long userId, String reason) {
        if (orderId == null || userId == null) {
            return false;
        }

        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return false;
        }

        // 验证订单所有权
        if (!order.getUserId().equals(userId)) {
            throw new IllegalArgumentException("无权操作此订单");
        }

        // 只有已付款、已发货、已完成状态可以申请退款
        if (order.getOrderStatus() != 2 && order.getOrderStatus() != 3 && order.getOrderStatus() != 4) {
            throw new IllegalArgumentException("该订单状态不允许申请退款");
        }

        // 这里应该调用退款接口
        log.info("申请退款，订单ID: {}, 退款原因: {}, 金额: {}", orderId, reason, order.getPaymentAmount());

        // 模拟退款处理（实际应该更新为退款中状态，等待退款完成后再更新）
        // 这里简化处理，直接设置为已取消
        order.setOrderStatus(5); // 已取消
        order.setUpdateTime(LocalDateTime.now());
        int result = orderMapper.updateById(order);
        return result > 0;
    }
}
